// pages/have/authentication/authentication.js
const app = getApp();
import { get_esncode, certified } from '../../../api/api';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    nvabarData: {
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
      title: '认证  ', //导航栏 中间的标题
      img: "../../image/back.png"
    },
    realname: '',
    height: app.globalData.height * 2 + 30,
    chooseSelect: {
      id: -1,
      name: '请选择车型'
    },
    esn_code: '',
    carbrandlist: [],
    selectShow: false
  },

  onLoad: function (options) {
    app.showLoading();
    const that = this;
    get_esncode().then(res => {
      const data = res.data;
      const list = []
      for(let i in data) {
        const obj = {
          id: i,
          name: data[i]
        }
        list.push(obj);
      }
      that.setData({
        carbrandlist: list
      });
      app.hideLoading();
    })
  },

  // 点击下拉显示框
  selectTap() {
    this.setData({
      selectShow: !this.data.selectShow
    });
  },

  // 点击下拉列表
  optionTap(e) {
    // console.log(e.currentTarget.dataset);
    const res = e.currentTarget.dataset;
    this.setData({
      'chooseSelect.id': res.id,  
      'chooseSelect.name': res.name
    });
    this.selectTap();
  },
  obCode (e) {
    var esn_code = e.detail.value;
    this.setData({
      esn_code
    });
  },

  obName (e) {
    var realname = e.detail.value;
    this.setData({ realname });
  },

  submit () {
    const realname = this.data.realname;
    const carbrand = this.data.chooseSelect.id;
    const esn_code = this.data.esn_code;

    if (realname === '') {
      app.showToast('姓名不能为空!');
      return;
    }
    if (carbrand <= 0) {
      app.showToast('请选择车型!');
      return;
    }
    if (esn_code === '') {
      app.showToast('发动机号不能为空!');
      return;
    }
    app.showLoading();
    const data = {
      openid: app.globalData.openid,
      realname,
      carbrand,
      esn_code
    }
    certified(data).then(res => {
      app.hideLoading();
      // console.log(res);
      if (res.code === 0) {
        let total = parseInt(app.globalData.userInfo.total_point);
        app.globalData.userInfo.total_point = total + 150; 
        app.showToast('认证成功','success',500);
        setTimeout(() => {
          wx.navigateBack({ delta: 1 });
        },500);
      } else {
        app.showToast(res.msg);
      }
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    // console.log('退出')
  }

})